<template>
  <div
    class="purchase-products-list-component-page salesordeer-purchase-products"
  >
    <div class="block">
      <header class="blockOrder">
        <h2 class="required">
          {{ title ? title : '添加消耗产品' }}
        </h2>
      </header>
      <section class="salesorder-table">
        <el-row class="block-item">
          <el-col :span="12">
            <!-- <div>&nbsp;</div> -->
            <el-button type="primary" @click="onOpenImportProduct">
              模板导入
            </el-button>
            <el-divider direction="vertical" />
            <el-button type="text" @click="onGetProductTemplate">
              模板下载
            </el-button>
          </el-col>
          <el-col :span="12" class="right">
            <el-button type="primary" @click="onOpenProductDialog">
              添加销售产品
            </el-button>
          </el-col>
        </el-row>
        <el-editable
          :columns="SALESORDER_COLUMNS_PRODUCT"
          :payload="payload_products"
          :need-pagination="true"
          :row-class-name="'tableRowHospName'"
          height="400"
          @reload="reloadData"
        >
          <template #header-hospName="{ }">
            <span class="required">销售医院</span>
          </template>
          <template #default-productCount="{ row, $index }">
            <div>
              <el-input-number
                v-model="row.productCount"
                :step="1"
                size="medium"
                :min="0"
                :max="
                  Number(row.availableQuantity || 1) > 999999999
                    ? 999999999
                    : Number(row.availableQuantity || 1)
                "
                @change="onChangeCount(row, $index)"
              />
              <span class="availableQuantity"
                >可用量{{ Number(row.availableQuantity) || 0 }}</span
              >
            </div>
          </template>
          <template #default-validDate="{ row }">
            <span>{{ row.validDate || '' }} &nbsp;&nbsp;</span
            ><span v-if="row.isCloseValidDate" class="expiry_date"
              >(近效期)</span
            >
          </template>
          <template #default-hospName="{ row, $index }">
            <div class="hosp_name_box">
              <el-autocomplete
                v-model="row.hospName"
                :fetch-suggestions="querySearchAsync"
                placeholder="请输入内容"
                @select="handleSelect($event, row, $index)"
              ></el-autocomplete>
            </div>
          </template>

          <template #default-opt="{ row, $index }">
            <a href="javascript:;" @click="onDeleteProduct(row, $index)"
              >删除</a
            >
          </template>
          <!-- 给创建报台用的表格内表单 -->
        </el-editable>
      </section>
    </div>
    <upload
      ref="upload"
      :title-str="titleStr"
      :params="stepOneFormData"
      @repliceProducts="repliceProductsFn"
      @complete="getUploadProducts"
    />
  </div>
</template>

<script>
import { hospitalSearch } from '@api/m_mall_web_v1.js';
import upload from '@/components/sales-upload';
import { urlDownload } from '@const/utils';
import ElEditable from '@components/el-editable';
import { ProductAddDialogService } from '~/modules/product/product-salesorder-add.dialog';
import * as CONSTS from './purchase-products-list.const';
import { IndexService } from './purchase-products-list.service';
// import { debuglog } from 'util';
// import { setTimeout } from 'timers';
// eslint-disable-next-line import/extensions
import { numMulti } from '~/common';

const service = new IndexService();

export default {
  components: {
    ElEditable,
    upload
  },
  props: {
    titleStr: {
      type: String,
      default: '批发采购'
    },
    isCreateBill: {
      type: Boolean
    },
    stepOneFormData: {
      type: Object
    },
    products: {
      type: Array
    },
    type: {
      type: String,
      default: 'default'
    },
    operationType: String,
    title: String,
    supplierId: String,
    seqNoVoList: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data() {
    return {
      ...CONSTS,
      productsList: [],
      payload_products: {},
      pager: {
        number: 1,
        size: 20
      },
      // 由于更新数量的动态性，下标的切换要同步。故这样搞
      index: {
        start: 1,
        end: 1
      },
      restaurants: [],
      timeout: null
    };
  },
  computed: {
    productAddDialogService() {
      return new ProductAddDialogService(this.$axios, this.$store, {
        type: this.type
      });
    }
  },
  watch: {
    products: {
      handler(val) {
        if (val !== undefined) {
          this.productsList = val;
          this.productsList.forEach(p => {
            const newP = p;
            if (p.productPrice !== '待定' && p.productPrice !== null) {
              let priceCount = numMulti(p.productPrice, p.productCount);
              priceCount = Math.floor(numMulti(priceCount, 100)) / 100;
              if (Number.isInteger(priceCount)) {
                priceCount = `${priceCount.toString()}.00`;
              }
              newP.priceCount = priceCount;
            }
            // if (Number(p.availableQuantity) === 0) {
            //    this.productsList.splice(i,1)
            // }
          });
          const startIndex = (this.pager.number - 1) * this.pager.size;
          const endIndex = this.pager.number * this.pager.size;
          this.payload_products = service.getPayload(
            this.productsList,
            this.pager,
            startIndex,
            endIndex
          );
          this.payload_products.content.forEach((p, i) => {
            const newP = p;
            newP.index = i + 1;
            newP.oldProduct = p.productCount;
          });
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    hospitalSearch(queryString, cb) {
      this.$axios({
        url: hospitalSearch,
        method: 'post',
        data: {
          busModelCode: '2',
          hospitalName: queryString,
          supplierCode: this.supplierId
        }
      })
        .then(res => {
          if (res.data.code === '0') {
            const results = res.data.payload || [];
            results.forEach(p => {
              const newP = p;
              newP.value = newP.hospitalName;
              newP.address = newP.hospitalCode;
            });
            cb(results);
          }
        })
        .catch(() => {})
        .finally(() => {});
    },
    querySearchAsync(queryString, cb) {
      this.hospitalSearch(queryString, cb);
    },
    handleSelect($event, row, $index) {
      this.$nextTick(() => {
        this.productsList.forEach((p, i) => {
          const newP = p;
          if (i === $index) {
            newP.hospName = $event.value;
          }
        });
      });
      this.$emit('removeSeqNoVoList', false);
      this.$emit('update:products', this.productsList);
    },
    repliceProductsFn() {
      this.productsList = [];
      this.pager.number = 1;
      this.$emit('update:products', this.productsList);
    },
    getUploadProducts(payload) {
      const loadProductList = payload;
      if (loadProductList.length > 0) {
        this.updateProductData(payload, true);
      }
    },
    // 前端分页逻辑
    reloadData(pager) {
      const startIndex = (pager.number - 1) * pager.size;
      const endIndex = pager.number * pager.size;
      this.payload_products = service.getPayload(
        this.productsList,
        pager,
        startIndex,
        endIndex
      );
      this.pager = pager;
      this.payload_products.content.forEach((p, i) => {
        const newP = p;
        newP.index = i + 1;
      });
    },
    onDeleteProduct(row, index) {
      if (this.seqNoVoList.length > 0) {
        this.$confirm(`确定修改产品吗，将清空已添加的序列号`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            const startIndex = (this.pager.number - 1) * this.pager.size;
            const endIndex = this.pager.number * this.pager.size;
            this.productsList.splice(startIndex + index, 1);
            this.payload_products = service.getPayload(
              this.productsList,
              this.pager,
              startIndex,
              endIndex
            );
            if (this.payload_products.content.length === 0) {
              // 如果当前获取的内容为空，那么要重新获取一下数据
              this.pager.number -= 1;
              if (this.pager.number <= 0) this.pager.number = 1;
              // eslint-disable-next-line no-shadow
              const startIndex = (this.pager.number - 1) * this.pager.size;
              // eslint-disable-next-line no-shadow
              const endIndex = this.pager.number * this.pager.size;
              this.payload_products = service.getPayload(
                this.productsList,
                this.pager,
                startIndex,
                endIndex
              );
            }
            this.$emit('removeSeqNoVoList', false);
            this.$emit('update:products', this.productsList);
          })
          .catch(() => {
            //
          });
      } else {
        const startIndex = (this.pager.number - 1) * this.pager.size;
        const endIndex = this.pager.number * this.pager.size;
        this.productsList.splice(startIndex + index, 1);
        this.payload_products = service.getPayload(
          this.productsList,
          this.pager,
          startIndex,
          endIndex
        );
        if (this.payload_products.content.length === 0) {
          // 如果当前获取的内容为空，那么要重新获取一下数据
          this.pager.number -= 1;
          if (this.pager.number <= 0) this.pager.number = 1;
          // eslint-disable-next-line no-shadow
          const startIndex = (this.pager.number - 1) * this.pager.size;
          // eslint-disable-next-line no-shadow
          const endIndex = this.pager.number * this.pager.size;
          this.payload_products = service.getPayload(
            this.productsList,
            this.pager,
            startIndex,
            endIndex
          );
        }
      }
    },
    onChangeCount(row, index) {
      const newRow = row;
      const oldProducts = row.oldProduct;
      if (this.seqNoVoList.length > 0) {
        this.$confirm(`确定修改产品吗，将清空已添加的序列号`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            if (
              Number(row.productCount) === 0 ||
              row.productCount === undefined
            ) {
              const { oldProduct } = row;
              this.$nextTick(() => {
                newRow.productCount = oldProduct;
              });
            }
            if (!Number.isInteger(Number(row.productCount))) {
              if (Number(row.productCount) > 0) {
                const { length } = row.productCount.toString().split('.')[1];
                if (length > 4) {
                  this.$nextTick(() => {
                    // row.productCount = Math.floor((Number(row.productCount) * 10000)) / 10000
                    newRow.productCount =
                      Math.floor(numMulti(row.productCount, 10000)) / 10000;
                  });
                }
              }
            }
            // 计算价格
            if (row.productPrice !== '待定') {
              this.productsList.forEach((p, i) => {
                const newP = p;
                if (i === index) {
                  let priceCount = numMulti(p.productPrice, p.productCount);
                  priceCount = Math.floor(numMulti(priceCount, 100)) / 100;
                  if (Number.isInteger(priceCount)) {
                    priceCount = `${priceCount.toString()}.00`;
                  }
                  this.$nextTick(() => {
                    newP.priceCount = priceCount;
                  });
                }
              });
            }
            this.$emit('removeSeqNoVoList', false);
            this.$emit('update:products', this.productsList);
          })
          .catch(() => {
            // let oldProduct = row.oldProduct;
            this.$nextTick(() => {
              newRow.productCount = oldProducts;
            });
          });
      } else {
        if (Number(row.productCount) === 0 || row.productCount === undefined) {
          const { oldProduct } = row;
          this.$nextTick(() => {
            newRow.productCount = oldProduct;
          });
        }
        if (!Number.isInteger(Number(row.productCount))) {
          if (Number(row.productCount) > 0) {
            const { length } = row.productCount.toString().split('.')[1];
            if (length > 4) {
              this.$nextTick(() => {
                // row.productCount = Math.floor((Number(row.productCount) * 10000)) / 10000
                newRow.productCount =
                  Math.floor(numMulti(row.productCount, 10000)) / 10000;
              });
            }
          }
        }
        // 计算价格
        if (row.productPrice !== '待定') {
          this.productsList.forEach((p, i) => {
            const newP = p;
            if (i === index) {
              let priceCount = numMulti(p.productPrice, p.productCount);
              priceCount = Math.floor(numMulti(priceCount, 100)) / 100;
              if (Number.isInteger(priceCount)) {
                priceCount = `${priceCount.toString()}.00`;
              }
              this.$nextTick(() => {
                newP.priceCount = priceCount;
              });
            }
          });
        }
        this.$emit('update:products', this.productsList);
      }
    },
    onOpenProductDialog() {
      // 这里的formData传递完整的数据，再在子组件内整理成子级组件想要的数据格式，
      // 实际上这样做是“不好的”，但是由于数据的复杂度和混乱度，故此选择。
      // 再有一个原因是，产品搜索列表还需要一些额外的参数
      if (this.seqNoVoList.length > 0) {
        this.$confirm(`确定修改产品吗，将清空已添加的序列号`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.productAddDialogService
              .create({
                title: '添加销售产品',
                query: {
                  operationType: this.operationType,
                  formData: this.stepOneFormData
                },
                confirmButtonClickHandler: (data = {}) => {
                  data.forEach(element => {
                    this.$set(element, 'productCount', 1);
                  });
                  this.updateProductData(data);
                }
              })
              .mount();
          })
          .catch(() => {
            //
          });
      } else {
        this.productAddDialogService
          .create({
            title: '添加销售产品',
            query: {
              operationType: this.operationType,
              formData: this.stepOneFormData
            },
            confirmButtonClickHandler: (data = {}) => {
              data.forEach(element => {
                this.$set(element, 'productCount', 1);
              });
              this.updateProductData(data);
            }
          })
          .mount();
      }
    },
    updateProductData(data, isImport) {
      this.productsList = service.reConcatSelectData(
        data,
        this.productsList,
        'originalFactoryProductCode',
        'batchNo',
        isImport
      );
      const startIndex = (this.pager.number - 1) * this.pager.size;
      const endIndex = this.pager.number * this.pager.size;
      this.payload_products = service.getPayload(
        this.productsList,
        this.pager,
        startIndex,
        endIndex
      );
      this.$emit('removeSeqNoVoList', false);
      this.$emit('update:products', this.productsList);
    },
    onOpenImportProduct() {
      if (this.productsList.length > 0) {
        let messageWord = '确定模板导入，将清空列表已添加的销售产品';
        if (this.seqNoVoList.length > 0) {
          messageWord += '和已导入的序列号';
        }
        this.$confirm(`${messageWord}?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.$refs.upload.dialog_visible = true;
            this.$emit('removeSeqNoVoList', true);
          })
          .catch(() => {
            //
          });
      } else {
        this.$refs.upload.dialog_visible = true;
      }
    },
    onGetProductTemplate() {
      urlDownload(
        'https://mt.heng-tai.com.cn/guoke-channel-aggregation-center/api/v1/files/download/qp5s099o0wkzxba5s1qd1vq5t2qce9ky.xlsx'
      );
    }
  }
};
</script>
<style lang="less">
.availableQuantity {
  color: red;
}
.hosp_name_box {
  position: relative;
  .el-autocomplete {
    width: 260px;
  }
  .required_ele {
    color: red;
    font-size: 22px;
  }
  .tableRowHospName {
    .tabel-table_2_column_20 {
      .cell {
        color: red !important;
      }
    }
  }
}
.expiry_date {
  color: red;
}
.salesordeer-purchase-products .salesorder-table {
  height: 600px;
}
</style>
